package de.jmda.core.util.classpath;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import de.jmda.core.util.RuntimeUtil;

class ResourceContainerDirectory
		extends ResourceContainerBase
{
	private String containerFileName;

	private int containerFileNameLength;

	ResourceContainerDirectory(File containerFile)
  {
    super(containerFile);
    
    if (containerFile.isDirectory() == false)
    {
      throw new ExceptionInInitializerError(
          containerFile.getName() + " is not a directory");
    }
    
    containerFileName =
				containerFile.getAbsolutePath().replace(RuntimeUtil.FILE_SEPARATOR, "/");
    
    containerFileNameLength = containerFileName.length();
  }

	@Override
  public Map<String, ClasspathResource> getClassPathResources()
  		throws IOException
  {
	  return
	  		getClassPathResources(ClasspathUtil.FILTER_ACCEPT_FILES_ALL);
  }

	public Map<String, ClasspathResource> getClassPathResources(
			FileFilter fileFilter) throws IOException
	{
		Map<String, ClasspathResource> result = new HashMap<>();

		Map<String, File> resourceFiles =
		    getResourceFilesByName(containerFile, fileFilter);

    for (String key : resourceFiles.keySet())
    {
    	ClasspathResourceFile value =
					new ClasspathResourceFile(
							new ResourceContainerDirectory(containerFile),
							resourceFiles.get(key));

    	result.put(value.getResourcename(), value);
    }
    
    return result;
  }

	private Map<String, File> getResourceFilesByName(
			File currentDirectory, FileFilter fileFilter)
			throws IOException
	{
		Map<String, File> result = new HashMap<>();
		
		for (File file : currentDirectory.listFiles())
		{
			// create new file without container file path
			String resourceFileName =
					file.getAbsolutePath().replace(RuntimeUtil.FILE_SEPARATOR, "/")
					    .substring(containerFileNameLength + 1);
			
			File resourceFile = new File(resourceFileName);

			if (file.isFile())
			{
				if (fileFilter.accept(resourceFile))
				{
					result.put(resourceFileName, resourceFile);
				}
			}
			else
			{
				if (fileFilter.accept(file))
				{
					result.put(resourceFileName, resourceFile);
					result.putAll(getResourceFilesByName(file, fileFilter));
				}
			}
		}
		
		return result;
	}
}